package com.personnel.code;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class ChkCoode
 */
@WebServlet("/ChkCoode")
public class ChkCoode extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ChkCoode() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//		1.定义底片宽高
		int width=80;
		int height=30;
//		2.创建底图
		BufferedImage image= new BufferedImage(width,height,BufferedImage.TYPE_INT_BGR);
//		3画笔
		Graphics g=image.getGraphics();
//		4 设置底色
		g.setColor(Color.BLACK);
//		5.画黑色的底图
		g.drawRect(0, 0, width, height);
//		6.底图写客户端   底图创建完毕可以查看
//		ImageIO.write(image, "jpeg", response.getOutputStream());

//		7。验证码
		String[] codes = {"0","1","2","3","4","5","6","7","8","9"};
		StringBuilder sb=new StringBuilder();
		Random r= new Random();
//		8.修改画笔颜色，准备些验证码
		g.setColor(Color.WHITE);
		
//		9.生成四位验证码
		for(int i=0; i<4;i++){
			int n= r.nextInt(10);
			String code=codes[n];
//			10把验证码写到底图上
			g.drawString(code, 20*i, 15);
//			11把验证码存起来
			sb.append(code);
		}
//		12把生成的验证码发送到session
		request.getSession().setAttribute("checkcode", sb.toString());
//		13设置响应内容为图片
		response.setContentType("image/jpeg");
//		14设置http报头，不允许缓存
		response.setDateHeader("expires", 0);
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Pragma","no-cache");
	
		ImageIO.write(image, "jpeg", response.getOutputStream());
	
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
